package cn.amarone.scaffold.config.global;

import cn.amarone.scaffold.config.annotation.Encrypt;
import cn.amarone.scaffold.config.business.common.BaseRsp;
import cn.amarone.scaffold.config.properties.EncryptProperties;
import cn.amarone.scaffold.util.AESUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author Amarone
 * @version 1.0
 * @description: 接口加密
 * @date 2023/8/25 17:14
 */
@EnableConfigurationProperties(EncryptProperties.class)
@ControllerAdvice
public class RspEncipher implements ResponseBodyAdvice<BaseRsp> {

    private ObjectMapper om = new ObjectMapper();
    @Autowired
    EncryptProperties encryptProperties;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return returnType.hasMethodAnnotation(Encrypt.class);
    }

    @Override
    public BaseRsp beforeBodyWrite(BaseRsp body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        byte[] keyBytes = encryptProperties.getKey().getBytes();
        try {
//            if (body.getMsg() != null) {
//                body.setMsg(AESUtils.encrypt(body.getMsg().getBytes(), keyBytes));
//            }
            if (body.getData() != null) {
                body.setData(AESUtils.encrypt(om.writeValueAsBytes(body.getData()), keyBytes));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return body;
    }
}
